package com.csr;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ChangeTransactionPin extends Dialog implements OnClickListener
{

	TextView dialogHeader;
	RelativeLayout mainLayout;
	LinearLayout layout_authenticate,layout_newPin;
	EditText etCurrentPin,etNewPin,etConfirmPin;
	Button btnOk,btnCancel;
	private ProgressDialog pd=null;
	Handler handler=new Handler();
	Context mContext;
	MD5Generator mD5Generator=new MD5Generator();
	HttpConn httpConn=new HttpConn();
	boolean isValidUser=false;
	public ChangeTransactionPin(Context context)
	{
		super(context);
		mContext=context;
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(com.csr.R.layout.change_pin);
		mainLayout=(RelativeLayout)findViewById(R.id.dialog_topup_root);
		layout_authenticate=(LinearLayout)findViewById(R.id.layout_authenticate);
		layout_newPin=(LinearLayout)findViewById(R.id.layout_newPin);
		
		etCurrentPin=(EditText)findViewById(R.id.etCurrentPin);
		btnOk=(Button)findViewById(R.id.btn_ok);
		btnCancel=(Button)findViewById(R.id.btn_Cancel);
		dialogHeader=(TextView)findViewById(R.id.dialog_header);
		dialogHeader.setText("Change Transaction Pin");
		 
		btnOk.setOnClickListener(this);
		btnCancel.setOnClickListener(this);
		
				
	}
	
	
	public void onClick(View v) 
	{
		// TODO Auto-generated method stub
		
	    if (v == btnOk)
		{
	    	 
	    	  
	    		 if(!isValidUser)
	    		 {
	    			 try
	    			 {
	    				 if(etCurrentPin.getText().toString().equals(""))
	    		                Toast.makeText(mContext,"Enter Current Pin",Toast.LENGTH_LONG).show();
	    				 else if(mD5Generator.MD5(etCurrentPin.getText().toString()).equals(AppData.getUserInfo().getTransactionPassword()))
		    			 {
	    					    isValidUser=true;
		    				 	dismiss();
								RelativeLayout ll=(RelativeLayout)findViewById(R.id.dialog_topup_root);
								ViewGroup.LayoutParams params=ll.getLayoutParams();
								params.height=params.height+80;
								ll.setLayoutParams(params);
								layout_authenticate.setVisibility(LinearLayout.GONE);
								layout_newPin.setVisibility(LinearLayout.VISIBLE);
								show();
 
		    			 }
		    			 else
		    			 {
		    				 handler.post(new Runnable() 
		    				 {
								public void run() 
								{
									// TODO Auto-generated method stub
								Toast.makeText(mContext, "Invalid Pin",Toast.LENGTH_SHORT).show();	
								etCurrentPin.setText("");
								}
							});
		    			 }
	    			 }
	    			 catch(Exception e)
	    			 {
	    				 e.printStackTrace();
	    			 }
		    		 
	    		 }
	    		 else
	    		 {
	    			 //requesting for new pin
	    			// Toast.makeText(mContext, "requesting new pin",Toast.LENGTH_SHORT).show();	
	    			 pd=ProgressDialog.show(mContext,    
							 null,"Please Wait..." , true);
	    			 pd.setContentView(R.layout.progress);
	    			 new Thread(ChangePin,"Change_pin").start();
	    		 }
	    	  
             
		}
	    else if(v==btnCancel)
		{
			dismiss();
		}
	}
	
	
	Runnable ChangePin=new Runnable()
	{
		
		public void run() 
		{
			try
			{
				
				
				etNewPin=(EditText)findViewById(R.id.etNewPin);
				etConfirmPin=(EditText)findViewById(R.id.etConfirmPin);
				
//				 String newPass=etNewPin.getText();
//                 String confimPass=etConfirmPin.getText();
				
				if(etNewPin.getText().toString().equals("")||
						etConfirmPin.getText().toString().equals(""))
				{
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							Toast.makeText(mContext, "Enter pin",Toast.LENGTH_SHORT).show();
						}
					});
				}
				else if(!etNewPin.getText().toString().equals(etConfirmPin.getText().toString()))
				{
					handler.post(new Runnable() 
					{
						public void run() 
						{
							pd.dismiss();
							System.out.println("new Pin:"+etNewPin.getText());
							System.out.println("Confirm pin:"+etConfirmPin.getText());
							Toast.makeText(mContext, "Pin not matching.",Toast.LENGTH_SHORT).show(); 
						}
					});
				}
				else
				{
					final String transactionPassword=mD5Generator.MD5(etNewPin.getText().toString());
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost(AppData.hostURL+"/WebService/iTopUp/csrapp.php");
					
					 UserInfo userInfo=AppData.getUserInfo();
                     String checksum=mD5Generator.MD5(mD5Generator.SHA1(userInfo.getLoginID()+"|"+userInfo.getLoginPin()+"|"+transactionPassword+"|"+userInfo.getpublickey()));
                     System.out.println("Check Sum:"+checksum);
                     
                     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
				        nameValuePairs.add(new BasicNameValuePair("function", "MobileChangePassword"));
				        nameValuePairs.add(new BasicNameValuePair("LoginId", userInfo.getLoginID()));
				        nameValuePairs.add(new BasicNameValuePair("MobilePassword", userInfo.getLoginPin()));
				        nameValuePairs.add(new BasicNameValuePair("TransactionPassword",transactionPassword));
				        nameValuePairs.add(new BasicNameValuePair("Checksum",checksum));
				        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				        ResponseHandler<String> responseHandler = new BasicResponseHandler();
				        String response = httpclient.execute(httppost,responseHandler);
				        System.out.println("Response:"+response);
				        
				        final JSONObject jsonObject=new JSONObject(response);
                        if(jsonObject.getString("ResponseCode").equals("000"))
                        {
                        	 handler.post(new Runnable() 
                        	 {
								public void run() 
								{
								
									AppData.getUserInfo().setTransactionPassword(transactionPassword);									
									pd.dismiss();
									dismiss();
									Toast.makeText(mContext, "Transaction Pin changed Successfully",Toast.LENGTH_SHORT).show();
								 }
							});
                        }
                        else
                        {
                        	handler.post(new Runnable() 
	                       	 {
									public void run() 
									{
										pd.dismiss();
										dismiss();
										try 
										{
											Toast.makeText(mContext, jsonObject.getString("ResponseDescription"),Toast.LENGTH_SHORT).show();
										}
										catch (JSONException e) 
										{
											// TODO Auto-generated catch block
											e.printStackTrace();
										}
									}
								});
                        }
				}
				
				
			}
			catch(final Exception e)
			{
				pd.dismiss();
				handler.post(new Runnable() 
              	 {
						public void run() 
						{
							pd.dismiss();
							dismiss();
							Toast.makeText(mContext,""+e.getMessage() ,Toast.LENGTH_SHORT).show();
						}
				 });
				e.printStackTrace();
			}
			
		}
	};
	
	 
	
}
